import React, { useEffect, useState, useRef } from 'react'

import { ConfigProvider, Button, DatePicker, Table, message } from 'antd';
import { SearchOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';

// 引入中文语言包-日期选择器
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import zhCN from 'antd/es/locale/zh_CN';

//列
import { columns } from '../../constant/riskColumn.js'

//api
import { getRecord, exportRecord, getAuthCode } from '../../utils/axiosRequest/api'

import styles from './index.module.css'

//取款记录显示
function TakeRecord() {
    //时间选择器
    const { RangePicker } = DatePicker;
    dayjs.locale('zh-cn'); // 全局设置为中文 
    //消息提示
    const [messageApi, contextHolder] = message.useMessage();
    //表格展示数据
    const [showDataSource, setDataSource] = useState([]);
    //默认一页面显示几条数据
    const [pageSize, setPageSize] = useState();
    //总共有多少条数据
    const [total, setTotal] = useState(0);
    const containerRef = useRef(null);
    //tab加载状态
    const [tableLoad, setTableLoad] = useState(false);
    //时间选择器
    const [time, setTime] = useState({
        startTime: '', endTime: ''
    });

    useEffect(() => {
        if (!containerRef.current) return;

        const calculatePageSize = () => {
            const { height } = containerRef.current.getBoundingClientRect();
            const rowHeight = 68;  // 预估行高
            const headerHeight = 100; // 表头高度
            const paginationHeight = 64; // 分页器高度（Ant Design 默认）

            // 计算可用高度（总高度 - 表头 - 分页器）
            const availableHeight = height - headerHeight - paginationHeight;
            const newPageSize = Math.max(1, Math.floor(availableHeight / rowHeight));

            setPageSize(newPageSize);
            initData(time.endTime, time.endTime, newPageSize, 1); // 加载第一页数据
        };

        // 初始化计算
        calculatePageSize();

        // 监听容器尺寸变化（可选，如果希望响应式调整）
        // const observer = new ResizeObserver(calculatePageSize);
        // observer.observe(containerRef.current);
        return () => {
            //observer.disconnect();
        }
    }, []); // 空依赖数组，确保只执行一次


    function initData(startTime, endTime, pageSize, pageIndex) {
        //获取用户基础信息
        setTableLoad(true)
        const params = new Map()
        params.set('pageSize', pageSize);
        params.set('pageIndex', pageIndex);
        params.set('startTime', startTime);
        params.set('endTime', endTime);
        getRecord(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    const total = data.data.total;//总条数
                    setTotal(total)
                    hadleData(data.data.recordLis)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
                setTableLoad(false)
            })
            .catch(error => {
                setTableLoad(false)
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //处理数据
    function hadleData(recordList) {
        const tempData = [];
        for (let i = 0; i < recordList.length; i++) {
            tempData.push({
                key: i,
                serial: i,
                withdrawalsName: recordList[i].withdrawalsName,
                idNumber: recordList[i].idNumber,
                bankName: recordList[i].bankName,
                branchName: recordList[i].branchName,
                districtsName: recordList[i].districtsName,
                branchAddress: recordList[i].branchAddress,
                phoneNumber: recordList[i].phoneNumber,
                withdrawalAmount: recordList[i].withdrawalAmount,
                currency: recordList[i].currency,
                withdrawalTime: recordList[i].withdrawalTime,
                transactionChannel: recordList[i].transactionChannel,
                withdrawalReason: recordList[i].withdrawalReason,
                cardIssuancePlace: recordList[i].cardIssuancePlace,
                isSelfWithdrawal: recordList[i].isSelfWithdrawal,
            })
        }
        setDataSource(tempData)
    }

    //点击了tab的分页器
    function handleTableChange(pagination, filters, sorter) {
        const current = pagination.current;//当前第几页
        //const pageSize = pagination.pageSize;//每页展示多少条
        initData(time.endTime, time.endTime, pageSize, current)
    };

    //时间选择器
    function onSelectDate(dates) {
        if (!dates) {
            messageApi.open({ type: 'success', content: '时间选择清空' });
            return;
        }
        // 解析成标准格式：YYYY-MM-DD HH:mm:ss
        const [start, end] = dates;
        const startTime = start.format('YYYY-MM-DD HH:mm:ss');
        const endTime = end.format('YYYY-MM-DD HH:mm:ss');
        setTime({ startTime: startTime, endTime: endTime })
    }

    //点击查询记录
    function searchRecord() {
        initData(time.startTime, time.endTime, pageSize, 1); // 加载第一页数据
    }

    //点击导出记录
    function exportExcel() {
        const params = new Map()
        getAuthCode(params)
            .then(response => {
                const data = response.data
                if (data.code === '000') {
                    //处理数据
                    const authCode = data.data.authCode;
                    downLoadFile(authCode)
                } else {
                    //处理失败
                    messageApi.open({ type: 'error', content: data.des });
                }
            })
            .catch(error => {
                messageApi.open({ type: 'error', content: error.message });
            });
    }

    //开始下载文件
    function downLoadFile(authCode) {
        window.open(exportRecord(authCode, time.startTime, time.endTime), '_blank');
    }

    return (
        <ConfigProvider locale={zhCN}>
            <div className={styles.container}>
                {contextHolder}
                <div className={styles.title_box}>
                    <div className={styles.range_picker_box}>
                        <RangePicker onChange={(dates) => { onSelectDate(dates) }} placeholder={['开始预约时间', '结束预约时间']} showTime />
                    </div>
                    <Button onClick={searchRecord} icon={<SearchOutlined />} type="primary" className={styles.template_padding}>查询记录</Button>
                    <Button onClick={exportExcel} icon={<DownloadOutlined />} className={styles.template_padding}>批量导出</Button>
                    <Button type="primary" icon={<ReloadOutlined />} >刷新</Button>
                </div>
                <div ref={containerRef} className={styles.data_box}>
                    <Table loading={tableLoad} scroll={{ x: 'max-content' }} onChange={handleTableChange} bordered={true}
                        pagination={{ defaultCurrent: '1', total: total, showSizeChanger: false, pageSize: pageSize }} dataSource={showDataSource} columns={columns} />
                </div>

            </div>
        </ConfigProvider>
    )
}

export default TakeRecord;